<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */

namespace MoChat\App\Client\Action\Dashboard\FollowRecord;

use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Client\Logic\FollowRecord\CreateLogic;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 跟进记录新-添加.
 * @Controller
 */
class NewCreate extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     * })
     *
     * @RequestMapping(path="/dashboard/client/followRecord/newCreate", methods="POST")
     */
    public function handle()
    {
        $user = user();
        if (empty($user)) {
            throw new CommonException(ErrorCode::AUTH_UNAUTHORIZED, '登入异常请重新登入');
        }
        // 请求参数
        $params = $this->request->all();
        // 校验参数
        $this->validated($params);
        $params['user'] = $user;
        Db::beginTransaction();
        try {
            Db::table('client_follow_record')
                ->insert([
                    'type' => $params['type'],
                    'client_id' => $params['clientId'],
                    'user_id' => Db::table('work_employee')->where('log_user_id', $params['user']['id'])->value('id'),
                    'remark' => $params['remark'],
                    'created_at' => date('Y-m-d H:i:s'),
                    'followed_at' => date('Y-m-d H:i:s'),
                    'returned_at' => $params['returnedAt'],
                ]);
            //追加到跟进任务
            Db::table('follow_tasks')
                ->updateOrInsert([
                    'client_id' => $params['clientId'],
                    'returned_at' => date('Y-m-d H:i:s'),
                    'status' => 0,
                ],[
                    'corp_id' => $user['corpIds'][0],
                    'returned_at' => date('Y-m-d H:i:s'),
                    'client_id' => $params['clientId'],
                    'status' => 1,
                    'returned_way' => $params['type'],
                    'created_at' => date('Y-m-d H:i:s'),
                ]);

            if (isset($params['returnedAt']) && $params['returnedAt']!==''){
                //下次回访任务
                Db::table('follow_tasks')
                    ->insert([
                        'corp_id' => $user['corpIds'][0],
                        'returned_at' => $params['returnedAt'],
                        'client_id' => $params['clientId'],
                        'status' => 0,
                        'returned_way' => $params['type'],
                        'created_at' => date('Y-m-d H:i:s'),
                    ]);
            }
            Db::table('client')
                ->where('id',$params['clientId'])
                ->update([
                    'level'=>$params['level']
                ]);
            Db::commit();
        } catch (\Throwable $ex) {
            Db::rollBack();
        }
        return [];
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'type' => 'integer',
            'clientId' => 'integer',
//            'returnedAt' => 'required'
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'type.integer' => '访问类型必须为整数',
            'clientId.integer' => '客户ID必须为整数',
//            'returnedAt.required' => '回访时间未填写',
        ];
    }
}
